package com.huichenghe.xinlvsh01.fragment;

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.huichenghe.xinlvsh01.CustomView.SleepDetaillView;
import com.huichenghe.xinlvsh01.DbEntities.MyDBHelperForDayData;
import com.huichenghe.xinlvsh01.R;
import com.google.android.gms.plus.PlusOneButton;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;

import java.util.Calendar;

/**
 * A fragment with a Google +1 button.
 * Activities that contain this fragment must implement the
 * {@link SleepingFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link SleepingFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class SleepingFragment extends Fragment {
    public static final String TAG = SleepingFragment.class.getSimpleName();

    private TextView deepHour, deepMinute, lightHour, lightMinute, hourAll, minuteAll;


    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";

    private SleepDetaillView histrogramSleep;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    // The URL to +1.  Must be a valid URL.
    private final String PLUS_ONE_URL = "http://developer.android.com";

    // The request code must be 0 or greater.
    private static final int PLUS_ONE_REQUEST_CODE = 0;


    private OnFragmentInteractionListener mListener;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment SleepingFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static SleepingFragment newInstance(String param1, String param2) {
        SleepingFragment fragment = new SleepingFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    public SleepingFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        if (getArguments() != null)
        {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_sleeping, container, false);
        initTheTextView(view);
        histrogramSleep = (SleepDetaillView)view.findViewById(R.id.zhuzhuangtu_sleep);
        // 查询数据库，截取前一天22:00到00:00的睡眠数据，再截取当天00:00到10:00大睡眠数据，拼接成整条睡眠数据
        // 获取用户名
        String userAccount = LocalDataSaveTool.getInstance(getContext()).readSp(MyConfingInfo.USER_ACCOUNT);
        Calendar calendar = Calendar.getInstance();
        int date = calendar.get(Calendar.DATE);
        int month = calendar.get(Calendar.MONTH) + 1;
        int year = calendar.get(Calendar.YEAR);
        // 今天日期
        String today = year + "-" + month + "-" + date;
        calendar.add(Calendar.DATE, -1);
        int datey = calendar.get(Calendar.DATE);
        int monthy = calendar.get(Calendar.MONTH) + 1;
        int yeary = calendar.get(Calendar.YEAR);



        // 昨天日期
        String yestoday = yeary + "-" + monthy + "-" + datey;
        // 昨天睡眠数据
        Cursor cursor = MyDBHelperForDayData.getInstance(getContext()).selectTheSleepData(getContext(), userAccount, yestoday);
        String yesterdayData = parseCursor(cursor);
        // 今天睡眠数据
        Cursor tCursor1 = MyDBHelperForDayData.getInstance(getContext()).selectTheSleepData(getContext(), userAccount, today);
        String todayData = parseCursor(tCursor1);

        // 截取昨天的数据, 从数据末尾截取12个字符，代表两个小时


        String y = "";
        if(yesterdayData.length() > 1)
        {
            String res = yesterdayData.replaceAll("\\d{12}$", "");
            y = yesterdayData.replaceAll(res, "");
        }


        // 截取今天的数据， 从数据开头截取60个字符，代表10小时
        String t = "";
        if(todayData.length() > 0)
        {
            t = todayData.substring(0, 60);
        }
        String allData = y + t;
        Log.i(TAG, "今天" + today + "昨天：" + yestoday);
        Log.i(TAG, "全部数据：" + allData);

        String dataSs = allData;
        String first = dataSs.replaceAll("^[0]+", "");                  // 去掉开头的0，
        String ridStart = first.replaceAll("^[3]+", "");                // 去掉开头的3，
        String alw = ridStart.replaceAll("^[0]+", "");
        String ridEnd = alw.replaceAll("[0]+$", "");               // 去掉结尾的0；
        ridEnd = ridEnd.replaceAll("[3]+$", "");                        // 去掉结尾的3；      // 这是最终的数据
        ridEnd = ridEnd.replaceAll("[0]+$", "");

        String onlyRidEnd = dataSs.replaceAll("[0]+$", "");
        onlyRidEnd = onlyRidEnd.replaceAll("[3]+$", "");

        int sleepTimeStart = (dataSs.length() - ridStart.length()) * 10;
        int sleepTimeEnd = (dataSs.length() - onlyRidEnd.length()) * 10;


        // 构造开始时间
        int invalidHour = sleepTimeStart / 60;
        int invalidMinute = sleepTimeStart % 60;
        int startHour = 22 + invalidHour;
        if(startHour > 24)
        {
            startHour = startHour - 24;
        }
        String startH = startHour + ":" + invalidMinute;
        // 构造结束时间

        int inHour = sleepTimeEnd / 60;
        int inMinute = sleepTimeEnd % 60;
        if(inMinute == 0)
        {
            if(inHour <= 10)
            {
                inHour = 10 - inHour;
            }
            else
            {
                inHour = 24 - (inHour - 10);
            }
        }
        else
        {
            if(inHour <= 10)
            {
                inHour = 10 - inHour - 1;
            }
            else
            {
                inHour = 24 - (inHour - 10) -1;
            }
            inMinute = 60 - inMinute;
        }


        String endH = inHour + ":" + inMinute;



        Log.i(TAG, "过滤后的睡眠数据：" + ridEnd);

        histrogramSleep.setSleepData(startH, endH, ridEnd);
        histrogramSleep.invalidate();

        // 更新显示, 获取深睡和浅睡时间

        int light = 0;  // 浅睡
        int deep = 0;   // 深睡
        char[] chars = ridEnd.toCharArray();
        for(int i = 0; i < chars.length; i++)
        {
            char d = chars[i];
            if(d == '1')
            {
                light ++;
            }
            else if(d == '2')
            {
                deep ++;
            }
        }
        if(light != 0)
        {
            light = light * 10;
        }
        if(deep != 0)
        {
            deep = deep * 10;
        }

        // 将数据转化为00h00'格式

        String[] lightSleep = tranlateToHourMinute(light);
        lightHour.setText(lightSleep[0] + getString(R.string.hour_has_prefix));
        lightMinute.setText(lightSleep[1] + getString(R.string.minute_has_prefix));

        String[] deepSleep = tranlateToHourMinute(deep);
        deepHour.setText(deepSleep[0] + getString(R.string.hour_has_prefix));
        deepMinute.setText(deepSleep[1] + getString(R.string.minute_has_prefix));


        String[] sleepAll = tranlateToHourMinute(light + deep);
        hourAll.setText(sleepAll[0]);
        minuteAll.setText(sleepAll[1]);


        return view;
    }

    private void initTheTextView(View view)
    {
        deepHour = (TextView)view.findViewById(R.id.deep_hour);
        deepMinute = (TextView)view.findViewById(R.id.deep_minute);
        lightHour = (TextView)view.findViewById(R.id.light_hour);
        lightMinute = (TextView)view.findViewById(R.id.light_minute);
        hourAll = (TextView)view.findViewById(R.id.hour_all);
        minuteAll = (TextView)view.findViewById(R.id.minute_all);

    }

    private String[] tranlateToHourMinute(int light)
    {
        String[] strArray = new String[2];
        String format = null;
        int hour = light / 60;
        int minute = light % 60;
        if (minute < 10) {
            format = "0" + minute;
        }
        else
        {
            format = String.valueOf(minute);
        }
        strArray[0] = String.valueOf(hour);
        strArray[1] = format;

     return strArray;
    }


    /**
     * 解析查询数据库返回的cursor
     * @param cursor
     * @return
     */
    private String parseCursor(Cursor cursor)
    {
        String data = "";
        if(cursor.getCount() != 0)
        {
            if(cursor.moveToFirst())
            {
                do {
                    data = cursor.getString(cursor.getColumnIndex("sleepData"));
                }while (cursor.moveToNext());
            }
        }
        return  data;
    }

    @Override
    public void onResume() {
        super.onResume();

    }

    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p/>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        public void onFragmentInteraction(Uri uri);
    }

    public void updateSleepData(String day)
    {

    }



}
